package stardust.core.java.thread;

public class ProxyRunnable implements Runnable
{
  
  private ProxyRunnableCallback callback;
  
  protected ProxyRunnable(ProxyRunnableCallback callback)
  {
    this.callback = callback;
  }

  public void run()
  {
    Runnable runnable = null;
    
    try
    {
      while ((runnable = this.callback.onStart(this)) != null)
      {
        try
        {
          runnable.run();
          
          this.callback.onStop(this, null);
        }
        catch (Throwable e)
        {
          this.callback.onStop(this, e);
          
          if (e instanceof InterruptedException)
          {
            runnable = null;
            break;
          }
        }
      }
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
    
    if (runnable != null)
    {
      while (true)
      {
        System.out.println("error....");
        try
        {
          Thread.sleep(10);
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  public static interface ProxyRunnableCallback
  {
    
    Runnable onStart(ProxyRunnable proxy) throws InterruptedException;
    
    void onStop(ProxyRunnable proxy, Throwable exception);
    
  }

}
